#!/bin/bash

set -e

SCRIPTE_NAME=$0
DOMAIN=$1
DOMAIN_DIR="ingress-tls"

if [[ "$SCRIPT_NAME" =~ "^\/" ]];then
    echo "Please change execute path"
    exit 1
fi

if [ "x$DOMAIN" = "x" ];then
    echo "Please Input DOMAIN:"
    exit 0
fi

if [ -d $DOMAIN_DIR ];then
    echo "The PEM exists, Please rmove it $DOMAIN_DIR"
    exit 0
else
    mkdir -p $DOMAIN_DIR
fi


cd $DOMAIN_DIR

cat > openssl.cnf <<EOF
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = $DOMAIN
EOF

make_ca() {
    # 创建CA的私钥
    openssl genrsa -out ca.key 2048

    # 创建CA的证书请求文件
    openssl req -new -key ca.key \
                -subj "/C=CN/ST=ZJ/L=HZ/O=163yun.com/OU=163yun/CN=163yun.com/emailAddress=skiff@163yun.com" \
                -out ca.csr

    # CA自签证书
    openssl x509 -req -in ca.csr -signkey ca.key -out ca.crt -days 35600
}

make_server(){
    # 创建用户的私钥
    openssl genrsa -out ingress-server.key 2048

    # 创建用户的证书请求文件
    openssl req -new -key ingress-server.key \
                -subj "/C=CN/ST=ZJ/L=HZ/O=test.com/OU=test/CN=$DOMAIN/emailAddress=pritest@test.com" \
                -out ingress-server.csr  -config openssl.cnf

    # CA给用户的请求文件添加数字签名生产用户证书
    openssl x509 -req -CA ca.crt  -CAkey ca.key  -CAcreateserial -in ingress-server.csr -out ingress-server.crt -days 36500 -extensions v3_req -extfile openssl.cnf
    #openssl rsa -in ingress-server.key -pubout -out ingress-server.pem
}

main(){
    make_ca
    make_server
    echo "服务端证书: $DOMAIN_DIR/ingress-server.crt"
    echo "服务证书私钥: $DOMAIN_DIR/ingress-server.key"
    echo "CA证书: $DOMAIN_DIR/ca.crt"
}
main
